//
//  BOCImageDownloadTask.m
//  BOCImageTools
//
//  Created by LeungChaos on 16/5/11.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "BOCImageDownloadTask.h"
#import "BOCNetworkImageManager.h"
#import "UIImage+MultiFormat.h"

@interface BOCImageDownloadTask ()

/**
 *  BOCProgressHandler 下载进度模型
 */
@property (nonatomic, strong, nullable) BOCProgressHandler *progressHandler;

@property (copy, nonatomic) BOCDownloadImageSeccessBlock seccessBlock;

@property (copy, nonatomic) BOCDownloadImageFailErrorBlock errorBlock;

@end

@implementation BOCImageDownloadTask {
    BOOL cancelState;
}

- (instancetype)initWithUrl:(NSURL *)url progress:(BOCProgressHandlerProgressBlock)progressBlock session:(NSURLSession *)session seccess:(BOCDownloadImageSeccessBlock)seccessBlock fail:(BOCDownloadImageFailErrorBlock)errorBlock
{
    if (self = [super init])
    {
        _cancel = &cancelState;
        
        _identifier = objectKeyWithUrl(url);
        
        _downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            // complete状态
            
            /*
             当task被取消了之后
             task
             */
            
            if (error) {
                if (errorBlock) {
                    dispatch_mainQueue_safely_sync(^{
                        errorBlock(error,response);
                    });
                }
            } else {
                NSData *data = [NSData dataWithContentsOfURL:location];
                UIImage *image = [UIImage sd_imageWithData:data];
                if (image) {
                    // 图片保存到沙盒
                    [[BOCNetworkImageManager sharedManager].imageCacher saveImageData:data forURl:url];
                    if (seccessBlock) {
                        dispatch_mainQueue_safely_sync(^{
                            seccessBlock(image,response);
                        });
                    }
                } else {
                    if (errorBlock) {
                        dispatch_mainQueue_safely_sync(^{
                            NSError *cError = [NSError errorWithDomain:NSURLErrorDomain code:250 userInfo:@{@"info" : @"------- image data is nil -------" }];
                            errorBlock(cError,response);
                        });
                    }
                }
            }
            [self setCompleted:YES];
        }];
        
        [_downloadTask resume];

        if (progressBlock) {
            _progressHandler = [BOCProgressHandler progressHandlerWithProgressBlock:progressBlock task:_downloadTask];
        }
    }
    return self;
}

- (void)setCompleted:(BOOL)completed
{
    _completed = completed;
    if (_completed) {
        
    }
}

- (void)setCancel:(BOOL)cancel
{
    cancelState = cancel;
    
    if (_progressHandler) {
        [_progressHandler removeObservers];
    }
    [_downloadTask cancel];
}


- (void)dealloc
{
    BOCLog(@"%s",__func__);
}

@end
